<?php
// app/middleware/AuthMiddleware.php

namespace app\middleware;

use app\service\user\TokenService;
use app\service\factory\ResponseFactory;
use think\Response;

class AuthMiddleware
{
    protected $tokenService;

    public function __construct(TokenService $tokenService)
    {
        $this->tokenService = $tokenService;
    }

    public function handle($request, \Closure $next)
    {
        // 从请求头获取访问令牌
        $accessToken = $request->header('Authorization');

        // 如果没有提供令牌，返回401错误
        if (!$accessToken) {
            $response = ResponseFactory::error('未提供访问令牌', 401);
            return json($response, 401);
        }

        // 移除Bearer前缀（如果存在）
        $accessToken = str_replace('Bearer ', '', $accessToken);

        try {
            // 验证访问令牌
            $payload = $this->tokenService->validateAccessToken($accessToken);

            // 将用户ID和其他信息存储在请求对象中
            $request->user_id = $payload['user_id'];
            $request->payload = $payload;
        } catch (\Exception $e) {
            $response = ResponseFactory::error($e->getMessage(), $e->getCode() ?: 401);
            return json($response, 401);
        }

        return $next($request);
    }
}
